﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Text;

namespace AutoUnitTestEngine.Helpers
{
    public class DataConvertHelper
    {
        private const string FG = "|";

        /// <summary>
        /// 把DataTable转换成Hashtable(Key为比较的条件也可以看个对象进行检索的唯一索引)
        /// </summary>
        /// <param name="dtScouce"></param>
        /// <param name="scKeyColNames"></param>
        /// <param name="htDataResult"></param>
        public static void DataTableToHashtableByKeyColNames(DataTable dtScouce,
                                                             StringCollection scKeyColNames
                                                             , out Hashtable htDataResult)
        {
            DataTableToHashtableByKeyColNames(dtScouce.Rows, scKeyColNames, out htDataResult);
        }

        /// <summary>
        /// 把DataTable转换成Hashtable(Key为比较的条件也可以看个对象进行检索的唯一索引)
        /// </summary>
        /// <param name="objDataRows"></param>
        /// <param name="scKeyColNames"></param>
        /// <param name="htDataResult"></param>
        public static void DataTableToHashtableByKeyColNames(ICollection objDataRows,
                                                             StringCollection scKeyColNames
                                                             , out Hashtable htDataResult)
        {
            htDataResult = new Hashtable();
            foreach (object obj in objDataRows)
            {
                if (obj is DataRow)
                {
                    var r = obj as DataRow;
                    string keyValue = "";
                    for (int i = 0; i < scKeyColNames.Count; i++)
                    {
                        if (keyValue.Length > 0) keyValue += FG;
                        keyValue += Convert.ToString(r[scKeyColNames[i]]);
                    }
                    htDataResult.Add(keyValue, r);
                }
            }
        }

        public static string StringCollectionToString(StringCollection sc)
        {
            var sbVal = new StringBuilder();
            foreach(string str in sc)
            {
                sbVal.Append((sbVal.Length == 0) ? str : "," + str);
            }
            return sbVal.ToString();
        }
    }
}